﻿using System;
using System.Web;
using System.Web.UI;
using System.IO;
using System.Web.UI.WebControls;
using System.Data;
using System.Text;

namespace DotNet.Utilities
{
    /// <summary>
    /// 导出为Excel
    /// 
    /// 2013-12-31 00:15 增加了适用于cs结构的导出函数by liuwentao
    /// </summary>
    public class ExportExcel
    {

        #region WEB应用
        protected void ExportData(string strContent, string FileName)
        {

            FileName = FileName + DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString() + DateTime.Now.Day.ToString() + DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString() + DateTime.Now.Second.ToString() + DateTime.Now.Millisecond.ToString();

            HttpContext.Current.Response.Clear();
            HttpContext.Current.Response.Charset = "gb2312";
            HttpContext.Current.Response.ContentType = "application/ms-excel";
            HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.UTF8;
            //this.Page.EnableViewState = false; 
            // 添加头信息，为"文件下载/另存为"对话框指定默认文件名 
            HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=" + FileName + ".xls");
            // 把文件流发送到客户端 
            HttpContext.Current.Response.Write("<html><head><meta http-equiv=Content-Type content=\"text/html; charset=utf-8\">");
            HttpContext.Current.Response.Write(strContent);
            HttpContext.Current.Response.Write("</body></html>");
            // 停止页面的执行 
            //Response.End();
        }

        /// <summary>
        /// 导出Excel
        /// </summary>
        /// <param name="obj"></param>
        public void ExportData(GridView obj)
        {
            try
            {
                string style = "";
                if (obj.Rows.Count > 0)
                {
                    style = @"<style> .text { mso-number-format:\@; } </script> ";
                }
                else
                {
                    style = "no data.";
                }

                HttpContext.Current.Response.ClearContent();
                DateTime dt = DateTime.Now;
                string filename = dt.Year.ToString() + dt.Month.ToString() + dt.Day.ToString() + dt.Hour.ToString() + dt.Minute.ToString() + dt.Second.ToString();
                HttpContext.Current.Response.AddHeader("content-disposition", "attachment; filename=ExportData" + filename + ".xls");
                HttpContext.Current.Response.ContentType = "application/ms-excel";
                HttpContext.Current.Response.Charset = "GB2312";
                HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
                StringWriter sw = new StringWriter();
                HtmlTextWriter htw = new HtmlTextWriter(sw);
                obj.RenderControl(htw);
                HttpContext.Current.Response.Write(style);
                HttpContext.Current.Response.Write(sw.ToString());
                HttpContext.Current.Response.End();
            }
            catch
            {
            }
        }
        #endregion
        /// <summary>
        /// 导出DataTable到一个文件中,使用特殊的分隔符
        /// </summary>
        /// <param name="dataSouce"></param>
        /// <param name="fileName"></param>
        public void ExportData(DataTable dataSouce, string fileName, string split)
        {
            var builder = new StringBuilder();
            bool isFirst = true;
            using (StreamWriter writer = new StreamWriter(fileName, false, Encoding.UTF8))
            {
                foreach (DataRow row in dataSouce.Rows)
                {
                    builder.Clear();
                    isFirst = true;
                    foreach (DataColumn col in dataSouce.Columns)
                    {
                        builder.Append(isFirst ? row[col] : split + row[col]);
                        if (isFirst)
                        {
                            isFirst = false;
                        }
                    }
                    writer.WriteLine(builder);
                }
            }

        }

        /// <summary>
        /// 将数据源导出为csv文件
        /// </summary>
        /// <param name="dataSource">数据</param>
        /// <param name="fileName">文件名</param>
        public void ExportCsv(DataTable dataSource, string fileName)
        {
            ExportData(dataSource, fileName, ",");
        }
    }
}